package yams.service.impl;

import com.google.common.collect.Lists;
import javafx.util.Callback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import yams.callback.IdCallback;
import yams.common.IRepository;
import yams.common.InfoPage;
import yams.domain.*;
import yams.repository.ICheckmeterRepository;
import yams.service.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 抄表服务实现
 * Created by Luffy on 2017/06/13.
 */
@Service("checkmeterService")
public class DefaultCheckmeterService implements ICheckmeterService {

    @Autowired
    private ICheckmeterRepository checkmeterRepository;
    @Autowired
    private IApartmentService apartmentService;
    @Autowired
    private IHouseService houseService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private IBillService billService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IdCallback idCallback;

    @Override
    public IRepository<CheckmeterEntity> getRepository() {
        return checkmeterRepository;
    }

    /**
     * 查询抄表记录
     *
     * @param checkmeterEntity
     * @return
     */
    @Override
    public InfoPage<CheckmeterEntity> queryCheckmeter(CheckmeterEntity checkmeterEntity) {

        Map<String, Object> conditionMap = checkmeterEntity.getProperties();
        Integer status = Integer.valueOf(conditionMap.get("filterFlag").toString());
        final String year = (String) conditionMap.get("meterYear");
        final String month = (String) conditionMap.get("meterMonth");
        Integer pageNumber = (Integer) conditionMap.get("pageNumber");
        Integer pageSize = (Integer) conditionMap.get("pageSize");
        String manager= conditionMap.get("_manager") == null ? "" : conditionMap.get("_manager").toString();

        List<String> houseIdList = Lists.newArrayList();
        if (conditionMap.get("houseId") != null && !Objects.equals("", conditionMap.get("houseId"))) {//选择了具体房屋
            houseIdList.add(conditionMap.get("houseId").toString());
        } else if (conditionMap.get("apartmentId") != null && !Objects.equals("", conditionMap.get("apartmentId"))) {//选择了具体公寓
            String apartmentId = conditionMap.get("apartmentId").toString();
            ApartmentEntity apartmentEntity = apartmentService.findById(apartmentId);
            Set<HouseEntity> houseEntitySet = apartmentEntity.getHouses();
            houseIdList = houseEntitySet.stream().map(house -> house.getId()).collect(Collectors.toList());
        }

        List<Object[]> list = Lists.newArrayList();
        Long total = 0L;
        if (CollectionUtils.isEmpty(houseIdList)) {
            if(StringUtils.isEmpty(manager)){
                list = checkmeterRepository.queryCheckmeter(status, year, month, pageNumber, pageSize);
                total = checkmeterRepository.countCheckmeter(status, year, month);
            }else{
                list = checkmeterRepository.queryCheckmeter(status, year, month, pageNumber, pageSize,manager);
                total = checkmeterRepository.countCheckmeter(status, year, month,manager);
            }
        } else {
            if(StringUtils.isEmpty(manager)){
                list = checkmeterRepository.queryCheckmeter(status, year, month, pageNumber, pageSize, houseIdList);
                total = checkmeterRepository.countCheckmeter(status, year, month, houseIdList);
            }else{
                list = checkmeterRepository.queryCheckmeter(status, year, month, pageNumber, pageSize, houseIdList,manager);
                total = checkmeterRepository.countCheckmeter(status, year, month, houseIdList,manager);
            }
        }

        List<CheckmeterEntity> reusltList = list.stream().map(item -> {
            CheckmeterEntity checkmeter = new CheckmeterEntity();
            checkmeter.setId(item[0] == null ? null : item[0].toString());
            checkmeter.setWater(item[1] == null ? null : item[1].toString());
            checkmeter.setElectric(item[2] == null ? null : item[2].toString());
            checkmeter.setGas(item[3] == null ? null : item[3].toString());
            checkmeter.setMeterYear(year);
            checkmeter.setMeterMonth(month);
            checkmeter.setMeterDay(item[6] == null ? null : item[6].toString());
            checkmeter.setHouseId(item[7].toString());
            //区分抄表房屋的标识
            HouseEntity houseEntity=houseService.findById(checkmeter.getHouseId());
            ApartmentEntity apartmentEntity=apartmentService.findById(houseEntity.getApartmentId());
            checkmeter.setHouseIdentites(apartmentEntity.getName()+"-"+houseEntity.getHouseNumber());
            checkmeter.setHouseName(item[8].toString());
            checkmeter.setName(item[9] == null ? null : item[9].toString());
            checkmeter.setCode(item[10] == null ? null : item[10].toString());
            checkmeter.setIsGenBill((item[11] != null && Objects.equals("Y", item[11])) ? "Y" : "N");
            checkmeter.getProperties().put("houseNumber",item[12] == null ? null : item[12].toString());

            CheckmeterEntity queryLastDataCondition = new CheckmeterEntity();
            int currentMonth = Integer.parseInt(month);
            if (currentMonth == 1) {//如果本月是1月，那上次日期就是去年12月份
                queryLastDataCondition.getProperties().put("meterYear", String.valueOf(Integer.parseInt(year) - 1));
                queryLastDataCondition.getProperties().put("meterMonth", 12);
                checkmeter.setLastDate(String.valueOf(Integer.parseInt(year) - 1) + "-" + 12);
            } else {
                queryLastDataCondition.getProperties().put("meterYear", year);
                queryLastDataCondition.getProperties().put("meterMonth", String.valueOf(currentMonth - 1));
                checkmeter.setLastDate(year + "-" + String.valueOf(currentMonth - 1));
            }
            queryLastDataCondition.getProperties().put("house_id_obj_ae", item[7].toString());
            List<CheckmeterEntity> lastList = listAll(queryLastDataCondition);
            if (lastList != null && lastList.size() > 0) {
                checkmeter.setLastMeterInfo(lastList.get(0).getWater()
                        + "," + lastList.get(0).getElectric()
                        + "," + lastList.get(0).getGas());
            } else {
                HouseEntity house = houseService.findById(checkmeter.getHouseId());
                ContractEntity contract = house.getContract();
                if (contract != null) {
                    checkmeter.setLastMeterInfo(contract.getWater()
                            + "," + contract.getElectric()
                            + "," + contract.getGas());
                } else {
                    checkmeter.setLastMeterInfo("0,0,0");
                }
            }
            return checkmeter;
        }).collect(Collectors.toList());

        return new InfoPage<CheckmeterEntity>(reusltList, total);
    }


    /**
     * 查询未抄表记录
     *
     * @param checkmeterEntity
     * @return
     */
    @Override
    public InfoPage<CheckmeterEntity> filterCheckmeter(CheckmeterEntity checkmeterEntity) {

        Map<String, Object> conditionMap = checkmeterEntity.getProperties();
        Integer status = Integer.valueOf(conditionMap.get("status").toString());
        final String year = (String) conditionMap.get("meterYear");
        final String month = (String) conditionMap.get("meterMonth");
        Integer pageNumber = (Integer) conditionMap.get("pageNumber");
        Integer pageSize = (Integer) conditionMap.get("pageSize");
        String manager= conditionMap.get("_manager") == null ? "" : conditionMap.get("_manager").toString();

        List<String> houseIdList = Lists.newArrayList();
        if (conditionMap.get("houseId") != null && !Objects.equals("", conditionMap.get("houseId"))) {//选择了具体房屋
            houseIdList.add(conditionMap.get("houseId").toString());
        } else if (conditionMap.get("apartmentId") != null && !Objects.equals("", conditionMap.get("apartmentId"))) {//选择了具体公寓
            String apartmentId = conditionMap.get("apartmentId").toString();
            ApartmentEntity apartmentEntity = apartmentService.findById(apartmentId);
            Set<HouseEntity> houseEntitySet = apartmentEntity.getHouses();
            houseIdList = houseEntitySet.stream().map(house -> {
                return house.getId();
            }).collect(Collectors.toList());
        }

        List<Object[]> list = Lists.newArrayList();
        Long total = 0L;
        if (CollectionUtils.isEmpty(houseIdList)) {
            if(StringUtils.isEmpty(manager)){
                list = checkmeterRepository.queryCheckmeter(status, year, month, pageNumber, pageSize);
                total = checkmeterRepository.countCheckmeter(status, year, month);
            }else{
                list = checkmeterRepository.queryCheckmeter(status, year, month, pageNumber, pageSize,manager);
                total = checkmeterRepository.countCheckmeter(status, year, month,manager);
            }

        } else {
            list = checkmeterRepository.queryCheckmeter(status, year, month, pageNumber, pageSize, houseIdList,manager);
            total = checkmeterRepository.countCheckmeter(status, year, month, houseIdList,manager);
        }

        final Integer[] subArray = new Integer[1];
        subArray[0] = 0;
        List<CheckmeterEntity> reusltList = list.stream().map(item -> {
            CheckmeterEntity checkmeter = new CheckmeterEntity();
            checkmeter.setId(item[0] == null ? null : item[0].toString());
            checkmeter.setWater(item[1] == null ? null : item[1].toString());
            checkmeter.setElectric(item[2] == null ? null : item[2].toString());
            checkmeter.setGas(item[3] == null ? null : item[3].toString());
            checkmeter.setMeterYear(year);
            checkmeter.setMeterMonth(month);
            checkmeter.setMeterDay(item[6] == null ? null : item[6].toString());
            checkmeter.setHouseId(item[7].toString());
            checkmeter.setHouseName(item[8].toString());
            checkmeter.setName(item[9] == null ? null : item[9].toString());
            checkmeter.setCode(item[10] == null ? null : item[10].toString());
            checkmeter.setIsGenBill((item[11] != null && Objects.equals("Y", item[11])) ? "Y" : "N");
            checkmeter.getProperties().put("houseNumber",item[12] == null ? null : item[12].toString());

            CheckmeterEntity temp = new CheckmeterEntity();
            int currentMonth = Integer.parseInt(month);
            if (currentMonth == 1) {//如果本月是1月，那上次日期就是去年12月份
                temp.getProperties().put("meterYear", String.valueOf(Integer.parseInt(year) - 1));
                temp.getProperties().put("meterMonth", 12);
                checkmeter.setLastDate(String.valueOf(Integer.parseInt(year) - 1) + "-" + 12);
            } else {
                temp.getProperties().put("meterYear", year);
                temp.getProperties().put("meterMonth", String.valueOf(currentMonth - 1));
                checkmeter.setLastDate(year + "-" + String.valueOf(currentMonth - 1));
            }
            temp.getProperties().put("house_id_obj_ae", item[7].toString());
            List<CheckmeterEntity> lastList = listAll(temp);
            if (lastList != null && lastList.size() > 0) {
                checkmeter.setLastMeterInfo("水表:" + lastList.get(0).getWater()
                        + ",电表:" + lastList.get(0).getElectric()
                        + ",燃气:" + lastList.get(0).getGas());
            } else {
                checkmeter.setLastMeterInfo("水表:0,电表:0,燃气:0");
            }

            return checkmeter;

        }).filter(item -> {
            if ((item.getWater() == null || "".equals(item.getWater()))
                    || (item.getElectric() == null || "".equals(item.getElectric()))
                    || (item.getGas() == null || "".equals(item.getGas()))) {

                return true;
            } else {
                subArray[0] = subArray[0] + 1;
                return false;
            }
        }).collect(Collectors.toList());

        return new InfoPage<CheckmeterEntity>(reusltList, total - subArray[0]);
    }

    /**
     * 为开通红包功能，临时生成30张账单，一天付一笔
     */
    public void test() {

        HouseEntity houseEntity = houseService.findById("b40f6211087f4adea2866e56202632e2");
        ContractEntity contractEntity = contractService.findById("b109e0dffdae44a598905b33787b071b");

        for (int i = 0; i < 30; i++) {
            BillEntity billEntity = new BillEntity();

            billEntity.setType(2);
            BigDecimal total = new BigDecimal(0);
            billEntity.setUser(userService.findById("c4ddf925fd2a47bcb7c7c194a9125ff1"));
            billEntity.setHouse(houseEntity);
            billEntity.setContract(contractEntity);

            LocalDate ld = LocalDate.now();
            billEntity.setCode("2" + contractEntity.getCode() + "-" + ld.toString().replace("-", "") + i);
            billEntity.setName(contractEntity.getHouseName() + ld.toString() + "水电气账单");

            billEntity.setWaterPrice(BigDecimal.ONE);
            billEntity.setElectricPrice(BigDecimal.ONE);
            billEntity.setGasPrice(BigDecimal.ONE);

            billEntity.setWaterNum(BigDecimal.ONE);
            billEntity.setPreWater(BigDecimal.ONE);
            billEntity.setGasNum(BigDecimal.ONE);
            billEntity.setPreGas(BigDecimal.ONE);
            billEntity.setElectricNum(BigDecimal.ONE);
            billEntity.setPreElectric(BigDecimal.ONE);

            if (billEntity.getWaterNum() != null) {
                billEntity.water();
                total = total.add(billEntity.getWaterAmount());
                contractEntity.setWater(billEntity.getWaterNum().doubleValue());
            }
            if (billEntity.getElectricNum() != null) {
                billEntity.electric();
                total = total.add(billEntity.getElectricAmount());
                contractEntity.setElectric(billEntity.getElectricNum().doubleValue());
            }
            if (billEntity.getGasNum() != null) {
                billEntity.gas();
                total = total.add(billEntity.getGasAmount());
                contractEntity.setGas(billEntity.getGasNum().doubleValue());
            }

            billEntity.setStatus(0);
            billEntity.setTotalAmount(new BigDecimal("0.1"));
            if (billEntity.getDiscount() != null) {
                billEntity.setActualAmount(billEntity.getTotalAmount().multiply(billEntity.getDiscount()));
            } else {
                billEntity.setActualAmount(billEntity.getTotalAmount());
            }
            billService.getRepository().saveEntity(billEntity, new Callback[]{idCallback});
        }

    }

}
